﻿/*

	(c) Sense Studios 2008 - 2011
	Sense Studios (http://www.sense-studios.com) all rights reserverd
	Part of Infinite Canvas
	 
	Written by Daan Nolen	 
 
 	The Background class will not only allow you to draw a different set
	of backgrounds, gradients etc. it will also allow you to load
	different images onto your canvas setting them to a 'parallaxed'
	background, meaning that some layers will move faster then others
 
*/

package com.sense.canvas { 

	import flash.display.*
	import flash.events.*
	import flash.text.*
	import flash.geom.*
	import flash.ui.Mouse;
	import flash.net.*
	import flash.geom.Matrix;
	import flash.system.Security;
	import flash.utils.Timer
	import flash.display.GradientType
	import flash.geom.Matrix
	
	// for zip files
	import com.sense.utils.fzip.FZip
	import com.sense.utils.fzip.FZipFile
	
	import com.sense.utils.BitmapManipulator
	import com.sense.canvas.*
	
	public class Background extends MovieClip {
		
				// background needs to moved completely to another class
		//public var background_image:String
		//public var background_image_width:int
		//public var background_image_height:int
		//public var backGroundContainer:Background
		//private var background:MovieClip
		
		private var Canvas
		private var template
		private var globalReference
		
		public var bgTemplate
		
		public var sizeX:int
		public var sizeY:int
		public var background_image:String
		public var background_image_width:int
		public var background_image_height:int
		
		private var parallaxX = 4  // needs to come from template
		private var parallaxY = 4  // needs to come from template
		private var layerArray:Array = []
		
		public function Background(canvas) {
			trace("background constructed on ", Canvas)
			
			this.Canvas = canvas
			setParams()
			
			//addChild(layer1)
			//addChild(layer2)
			//addChild(layer3)
			//addChild(layer4)
			//addChild(layer5)
			//addChild(layer6)
			
			//addEventListener(Event.ENTER_FRAME, updateBackground)
			addEventListener(Event.ADDED_TO_STAGE, init)
		}
		
		private function setParams() {
			this.template = Canvas.template
			this.globalReference = Canvas.globalReference
			this.sizeY = Canvas.sizeY
			this.sizeX = Canvas.sizeX
			this.background_image = Canvas.background_image
			this.background_image_width = Canvas.background_image_width
			this.background_image_height = Canvas.background_image_height
		}
		
		public function init(e:Event) { 
			globalReference = stage.getChildByName("globals")
			bgTemplate = globalReference.templates['backgroundTemplate']
			
			parallaxX = bgTemplate.parallaxX
			parallaxY = bgTemplate.parallaxY
			// trace("\n\n\n\n##################\n", bgTemplate.gradIsSet, parallaxX, parallaxY)
		
			bgTemplate.layers.forEach(buildLayers)
			
			function buildLayers(e, i, a) {
				layerArray.push( new Array( new MovieClip(), e.multiplyerX, e.multiplyerY ) )
				layerArray[i][0].name = e.name
				addChild(layerArray[i][0])
			}
				
			drawBackGround()
		}
		
		
		public function updateBackground(e:Event=null) {
			for (var i:uint=0; i < layerArray.length; i++) {
				layerArray[i][0].x = Math.round( Canvas.x / layerArray[i][1]  )
				layerArray[i][0].y = Math.round( Canvas.y / layerArray[i][2] )
			}
			//updateAfterEvent()
		}
		
		
		public function drawBackground():void {
			
			// create background object
			background = new MovieClip()
			allContainer.addChild(background)
			
			background.name = "background"
			background.isDraggable = true
			
			// firstDraw some framework for the interaction
			background.graphics.beginFill(0x333333, 0.0);
			background.graphics.drawRect(0, 0, this.sizeX, this.sizeY);		

			//backGroundContainer = new Background(this)
			//parent.addChildAt(backGroundContainer, 0)
			
			trace("Canvas dispatched complete")
			// goTo(startX, startY)
			trace(startX, startY)
			setX = startX
			setY = startY
			
			dispatchEvent(new Event(Event.COMPLETE))
		}
		
		private function ioErrorHandler(e:Event) {
			trace("ERROR: CANVAS had load error ", e)
		}
		
		public function drawBackGround() {
			
			// dreadded crosses
			/*
			var cxLength:int = Math.ceil(sizeX/gX)
			var cyLength:int = Math.ceil(sizeY/gY)
			
			for (var cx = 0; cx < cxLength; cx++) {
				for (var cy = 0; cy < cyLength; cy++) {
					var cross:Sprite = new Sprite();
					cross.name = "cross_" + cx + "_" + cy
					cross.graphics.lineStyle(1, 0x666666, 1)
					
					cross.graphics.moveTo ( cx*gX, (cy*gY) -3 )
					cross.graphics.lineTo ( cx*gX, (cy*gY) +4 )
					cross.graphics.moveTo ( (cx*gX)-3, (cy*gY) )
					cross.graphics.lineTo ( (cx*gX)+4, (cy*gY) )
					
					background.addChild(cross)
				}
			}
			*/
			
			if (bgTemplate.gradIsSet == 'true') {
	 			// gradient
				var myMatrix:Matrix = new Matrix();
				trace(myMatrix.toString());          // (a=1, b=0, c=0, d=1, tx=0, ty=0)
				 
				myMatrix.createGradientBox(sizeX/parallaxX, sizeY/parallaxY, (Math.PI/2) , 0, int(bgTemplate.gradSpread) );
				 
				var colors:Array = [ int(bgTemplate.gradColor1), int(bgTemplate.gradColor2) ];
				var alphas:Array = [100, 100];
				var ratios:Array = [0, 0xFF];
				 
				layerArray[0][0].graphics.beginGradientFill(GradientType.LINEAR, colors, alphas, ratios, myMatrix);
				layerArray[0][0].graphics.drawRect(0, 0, sizeX, sizeY);
			
			// repetitive image
			}else if (template.background_image) {
				
				var fileFromZip:FZipFile = globalReference.stylingZip.getFileByName( background_image )
				var bgrLoader:Loader = new Loader()
				bgrLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, doLoadComplete)
				bgrLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
				// bgrLoader.load( new URLRequest(background_image) )
				
				bgrLoader.loadBytes(fileFromZip.content);
				
				function doLoadComplete(e:Event) {
					var cxLength:int = Math.ceil(sizeX / background_image_width)
					var cyLength:int = Math.ceil(sizeY / background_image_height)
					
					for (var cx:int = 0; cx < cxLength; cx++) {
						for (var cy:int = 0; cy < cyLength; cy++) {
							
							//var bgrBitmap = BitmapManipulator.mcToBitmap(bgrLoader, true, 0, 0, background_image_width, background_image_height, 1)							
							//bgrBitmap.name = "background"
							//bgrBitmap.x = cx * background_image_width
							//bgrBitmap.y = cy * background_image_height
							// layer1.addChild(bgrLoader)
						}
					}
					
					// removeLoading() 
					// trace("Canvas dispatched complete")
					// dispatchEvent(new Event(Event.COMPLETE))
				}
			
			// imagegrid
			}else if (template.backgroundImageGroup) {

				template.backgroundImageGroup.forEach(buildImage)
				var count:int = 0
				
				function buildImage(element, i, a) {
					trace(element, element.url, globalReference)
					
					var bgrLoader:Loader = new Loader()
					var fileFromZip:FZipFile = globalReference.stylingZip.getFileByName( element.url )
					
					//var bgrLoader:Loader = new Loader()
					
					// bgrLoader.load(new URLRequest( fileFromZip.content ))
					bgrLoader.loadBytes(fileFromZip.content)
					bgrLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, doLoadComplete)
					bgrLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
					
					function doLoadComplete(e:Event) {
						
						//var bgrBitmap = BitmapManipulator.simpleMcToBitmap(bgrLoader)
						//bgrLoader.name = "background"
						//bgrLoader.x = element[1]
						//bgrLoader.y = element[2]
						//background.addChild(bgrBitmap)
						//background.addChild(bgrLoader)
						trace(">>> ", bgrLoader, element.x, element.y)
						
						var bgrBitmap:MovieClip = new MovieClip() // BitmapManipulator.simpleMcToBitmap(bgrLoader)
						bgrLoader.mouseEnabled = false
						bgrBitmap.addChild(bgrLoader)
						bgrBitmap.name = "background"
						bgrBitmap.x = element.x
						bgrBitmap.y = element.y
						//layer1.addChild(bgrBitmap)
						
						count ++
						
						if (count == template.backgroundImageGroup.length) {
							trace("Canvas dispatched complete")
							dispatchEvent(new Event(Event.COMPLETE))
						}
					}
				}
			}
			
			bgTemplate.objects.forEach(buildObjects)
			
			function buildObjects(e, i, a) {
				var objectLoader = new Loader()
				
				if (e.random == 'false') {
					objectLoader.x = e.objectX
					objectLoader.y = e.objectY
				}else{
					objectLoader.x = Math.round( Math.random() * e.objectX )// + e.minObjectX
					objectLoader.y = Math.round( Math.random() * e.objectY ) //+ e.minObjectY
				}
				
				// where to put the object
				for (var j:uint=0; j < layerArray.length; j++) {
					
					// trace( "#######\n\n\n\n\n", layerArray[j][0].name, e.layer)
					// trace("#### checking: ", e.url, " into ", layerArray[j][0].name, " with ", e.layer)
					if (layerArray[j][0].name == e.layer) {
						trace("#### loading: ", e.url, " into ", e.layer)
						//trace("#### check X, Y: ", e.objectX, e.objectY, objectLoader.x, objectLoader.y )
						
						var fileFromZip:FZipFile = globalReference.stylingZip.getFileByName( e.url )
						
						//objectLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, doLoadComplete)
						//objectLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
				
						objectLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, function(e) { trace("we had a problem: ", e) } )
						objectLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(e) { trace("load completed with: ", e) } )
						
						//var objectLoader:Loader = new Loader()
						// bgrLoader.load( new URLRequest(background_image) )
						objectLoader.loadBytes(fileFromZip.content);
	
						
						
						// objectLoader.load(new URLRequest(e.url))
						layerArray[j][0].addChild(objectLoader)
					}
				}
			}
			
			
			/****
					
			/*
			// load some random clouds
			var wolk:String = "_styling/wolk.png"
			var ballon:String = "_styling/luchtballon.png"
			var lensFlare:String = "_styling/lensflare.png"
			var gras:String = "_styling/gras.png"
			
			for (var i:uint=0; i < 24; i++) {
				var wolkLoader:Loader = new Loader()
				wolkLoader.x = Math.round( Math.random() * 4000 )
				wolkLoader.y = Math.round( Math.random() * 4000 )
				var layerNum = Math.round( (Math.random() * 4) + 2)  // 2-6
				this["layer"+layerNum].addChild(wolkLoader)
				wolkLoader.load(new URLRequest(wolk))
			}
			
			var ballonLoader:Loader = new Loader()
			ballonLoader.load(new URLRequest(ballon))
			ballonLoader.x = Math.round( Math.random() * 2000 )
			ballonLoader.y = Math.round( Math.random() * 2000 )
			var layerNum = Math.round( (Math.random() * 3) + 1)  // 1-4
			this["layer"+layerNum].addChild(ballonLoader)
			
			var lensFlareLoader:Loader = new Loader()
			lensFlareLoader.load(new URLRequest(lensFlare))
			lensFlareLoader.x = Math.round( Math.random() * 1000 )
			lensFlareLoader.y = Math.round( Math.random() * 1000 )
			layer1.addChild(lensFlareLoader)
			
			var grasLoader:Loader = new Loader()
			grasLoader.load(new URLRequest(gras))
			grasLoader.x = 0
			grasLoader.y = 4800
			layer6.addChild(grasLoader)
			*/
		}
	
	}
}